package com.old.nsi_class.api;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.DB.JSONResult2;
import com.old.nsi_class.model.Image_model;

@WebServlet("/Class_image_api")
public class Class_Image extends HttpServlet {

	/**
	 * 序列化
	 */
	private static final long serialVersionUID = 1L;
	private Gson gson = new Gson();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.doPost(req, res);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		String whereFrom = req.getParameter("whereFrom");
		if("addImage".equals(whereFrom)) {
			addImage(req,res);
		}else if("delImage".equals(whereFrom)) {	
			delImage(req,res);
		}else if("get_list".equals(whereFrom)) {	
			getImageList(req,res);	
		}else {
			JSONResult2.toResultFault(req, res);
		}
	}
	
	/**
	 * 获取图片详情
	 * @param req
	 * @param res
	 * @throws IOException 
	 */
	private void getImageList(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String sql = "SELECT id,lowFile,bigFile,create_time FROM nsi_image ORDER BY create_time DESC ;";
		List<Image_model> list = Course_DB.searchImage(sql);
		int rowCount = Course_DB.count(sql);
		JSONResult2 json = new JSONResult2(rowCount,list);
		String data = gson.toJson(json);
		JSONResult2.toResult(req, res, data);
		
	}

	/**
	 * 删除方法
	 * @param req
	 * @param res
	 * @throws IOException 
	 */
	private void delImage(HttpServletRequest req, HttpServletResponse res) throws IOException {
		String id = req.getParameter("imageId");
		if(id!=null && id.length()>0) {
			String sql = "delete from nsi_image where id="+id+";";
			Course_DB.commonMethod(sql);
			JSONResult2 json = new JSONResult2();
			String data = gson.toJson(json);
			JSONResult2.toResult(req, res, data);
		}else {
			String msg = "参数不合法";
			JSONResult2 json = new JSONResult2(msg);
			String data = gson.toJson(json);
			JSONResult2.toResult(req, res, data);
		}
	}

	/**
	 * 添加方法
	 * @param req
	 * @throws IOException 
	 */
	private void addImage(HttpServletRequest req,HttpServletResponse res) throws IOException {
		String imageUrl=req.getParameter("imageurl");
		if(imageUrl!=null && imageUrl!=" ") {
			String sql = "insert into nsi_image values (null,null,'"+imageUrl+"',NOW());";
			Course_DB.commonMethod(sql);
			JSONResult2 json = new JSONResult2();
			String data = gson.toJson(json);
			JSONResult2.toResult(req, res, data);
		}else {
			String msg = "参数不合法";
			JSONResult2 json = new JSONResult2(msg);
			String data = gson.toJson(json);
			JSONResult2.toResult(req, res, data);
		}
	}
	
}
